/**
 *  题库相关的业务处理
 *  1  题库分类树展示以及维护
 *  2  分类下的题库展示
 *  3
 *
 * @type {exports}
 */
var express = require('express');
var mongoose = require('mongoose');
var async = require('async');
var url = require('url');
var mongoose = require('mongoose');
var util = require('../models/util');

require('../models/category.js');
require('../models/store.js');
require('../models/battle.js');

var Category = mongoose.model('Category');
var Store = mongoose.model('Store');
var Battle = mongoose.model('Battle');

var router = express.Router();

//获取题库信息
router.post('/getById', function(req, res){
    console.log(req.query);
    var storeId = req.query.storeId;
    console.log('storeId:' + storeId);
    Store.findById(storeId).exec(function(err, store){
        if(err){
            console.log(err);
        }
        console.log(store);
        res.send(store);
    });
});

//获取题库下正在进行的对战
router.post('/battles', function (req, res) {
    var query = req.query;
    console.log(query);

    var storeId = query.storeId;
    var skip = query.skip;
    var limit = query.limit;

    Battle.find({
        store: storeId,
        status : {
            $in : ['N','I']
        }
    }).sort({
        status : 'desc'
    }).sort({
        createTime: 'desc'
    }).skip(skip).limit(limit).populate('store').populate('owner')
        .populate('users').populate('fleeUsers')
        .exec(function (err, battles) {
        if (err) throw err;
        battles = util.toJSON(battles);
        res.send(battles);
    });
});

//我参与的挑战
router.post('/mybattles', function (req, res) {

    var query = req.query;
    console.log(query);
    var skip = query.skip;
    var limit = query.limit;

    var user = req.session.user;
    var userId = user._id;
    Battle.find({
        users : userId
    }).sort({
        createTime: 'desc'
    }).skip(skip).limit(limit).populate('store').populate('owner')
        .populate('users').exec(function (err, battles) {
        if (err) throw err;
        battles = util.toJSON(battles);
        for(var i = 0, len = battles.length; i<len; i++) {
            var b = battles[i];
            b.myScore = b.allScores ? b.allScores[userId] : 0;
        }
        console.log(battles);
        res.send(battles);
    });

});

module.exports = router;
